Ext.ns('Pohon.ux.form');

Pohon.ux.form.JPicker = Ext.extend(Ext.form.TriggerField, {

    /**
     * @cfg {String/Object} invalidText
     * Validation text
     */
    invalidText: "'{0}' is not a valid color - it must be in a the hex format (# followed by 3 or 6 letters/numbers 0-9 A-F)",
    /**
     * @cfg {String} triggerClass
     * An additional CSS class used to style the trigger button.  The trigger will always get the
     * class 'x-form-trigger' and triggerClass will be <b>appended</b> if specified (defaults to 'x-form-color-trigger'
     * which displays a color wheel icon).
     */
    triggerClass: 'x-form-color-trigger',
    
    /**
     * @cfg {String}
     * Path to Jpicker images, defaults to ./jpicker/images/
     */
    clientPath: '../../js/Extmx/picker/images/',
    // private
    defaultAutoCreate: {
        tag: "input",
        type: "text",
        size: "10",
        maxlength: "7",
        autocomplete: "off"
    },
    
    // Limit input to hex values
    maskRe: /[#a-f0-9]/i,
    
    // private
    validateValue: function(value){
        if (!Pohon.ux.form.JPicker.superclass.validateValue.call(this, value)) {
            return false;
        }
        if (value.length < 1) {// if it's blank and textfield didn't flag it then it's valid
            this.setColor('');
            return true;
        }
        
        var parseOK = this.parseColor(value);
        
        if (!value || (parseOK === false)) {
            this.markInvalid(String.format(this.invalidText, value));
            return false;
        }
        this.setColor(value);
        return true;
    },
    
    /**
     * Sets the current color and changes the background.
     * Does *not* change the value of the field.
     * @param {String} hex The color value.
     */
    setColor: function(color){
        if (color === '' || color === undefined) {
            if (this.emptyText !== '' && this.parseColor(this.emptyText)) {
                color = this.emptyText;
            }
            else {
                color = 'transparent';
            }
        }
        if (this.trigger) {
            this.trigger.setStyle({
                'background-color': color
            });
        }
        else {
            this.on('render', function(){
                this.setColor(color);
            }, this);
            
        }
    },
    
    // private
    // Provides logic to override the default TriggerField.validateBlur which just returns true
    validateBlur: function(){
        return !this.menu || !this.menu.isVisible();
    },
    
    /**
     * Returns the current value of the color field
     * @return {String} value The color value
     */
    getValue: function(){
        return Pohon.ux.form.JPicker.superclass.getValue.call(this) || "";
    },
    
    /**
     * Sets the value of the color field.  You can pass a string that can be parsed into a valid HTML color
     * <br />Usage:
     * <pre><code>
     colorField.setValue('#FFFFFF');
     </code></pre>
     * @param {String} color The color string
     */
    setValue: function(color){
        Pohon.ux.form.JPicker.superclass.setValue.call(this, this.formatColor(color));
        this.setColor(this.formatColor(color));
    },
    
    // private
    parseColor: function(value){
        return (!value || (value.substring(0, 1) != '#')) ? false : (value.length == 4 || value.length == 7);
    },
    
	// private
    colorToHex: function(color){
        if (color.substr(0, 1) === '#') {
            return color;
        }
        var digits = /(.*?)rgb\((\d+), (\d+), (\d+)\)/.exec(color);
        
        var red = parseInt(digits[2]);
        var green = parseInt(digits[3]);
        var blue = parseInt(digits[4]);
        
        var rgb = blue | (green << 8) | (red << 16);
        return digits[1] + '#' + rgb.toString(16);
    },
    
    // private
    formatColor: function(value){
		if (value && value.substring(0,3) == 'rgb') {
			value = this.colorToHex(value);
		}
		
        if (!value || this.parseColor(value)) {
            return value;
        }
        if (value.length == 3 || value.length == 6) {
            return '#' + value;
        }
        return '';
    },
    
    // private
    menuListeners: {
        select: function(e, c){
            this.setValue(c);
        },
        
        show: function(){// retain focus styling
            this.onFocus();
        },
        
        hide: function(){
            this.focus.defer(10, this);
            var ml = this.menuListeners;
            this.menu.un("select", ml.select, this);
            this.menu.un("show", ml.show, this);
            this.menu.un("hide", ml.hide, this);
        }
        
    },
    
    onTriggerClick: function(){
    
        //var m = new Ext.menu.Menu();
        var m = new Ext.Window({
            title: 'Select color',
            width: 560,
            height: 350,
            modal: true
        });
        var that = this;
        
        var color2color = function(color){
            var all = color.val('all');
            return all && '#' + all.hex || 'transparent';
        };
        
        var ccancel = function(color){
            m.destroy();
        };
        
        var ccommit = function(color){
            that.setValue(color2color(color));
            m.destroy();
        };
        
        var clive = function(color){
        };
        
        var color = this.parseColor(this.getValue());
        if (!color) {
            color = '000000';
        }
        else {
            color = this.getValue();
        }
        
        m.show();
        $(m.body.dom).jPicker({
            color: {
                active: new $.jPicker.Color({
                    hex: color
                })
            },
            images: {
                clientPath: this.clientPath
            }
        }, ccommit, clive, ccancel);
    }
    
});

Ext.reg('jpickerfield', Pohon.ux.form.JPicker);
